<template>
  <div class="fillcontain">
    <div class="table_container">
      <el-row>
        <el-button type="primary" @click="handleEdit(0, null,'add')">新增书籍</el-button>
      </el-row>
      <br/>
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading">
        <el-table-column label="封面">
          <template slot-scope="scope">
            <img :src="baseImgPath+'/api'+scope.row.photo.url" v-if="scope.row.photo != null" width="50" height="50"/>
          </template>
        </el-table-column>
        <el-table-column
          label="书名"
          prop="title">
        </el-table-column>

        <el-table-column
          label="作者"
          prop="author">
        </el-table-column>

        <el-table-column
          label="出版社"
          prop="press">
        </el-table-column>

        <el-table-column
          label="出版时间"
          prop="publicationTime">
        </el-table-column>

        <el-table-column
          label="简介"
          prop="des"
          :show-overflow-tooltip="true"
        >
        </el-table-column>

        <el-table-column
          label="语言"
          :formatter="languageFormat">
        </el-table-column>


        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row,'edit')">
              管理章节
            </el-button>
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row,'edit')">
              编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDeleteAlert( scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="Pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pages.page"
          :page-size="pages.pageSize"
          layout="total, prev, pager, next"
          :total="pages.total">
        </el-pagination>
      </div>

      <el-dialog :title="dialog.title" :visible.sync="dialog.dialogFormVisible" :close-on-click-modal="dialog.close">
        <el-form :model="article">

          <el-form-item label="书名" label-width="100px">
            <el-input v-model="article.title" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="作者" label-width="100px">
            <el-input v-model="article.author" auto-complete="off"></el-input>
          </el-form-item>

          <el-form-item label="出版社" label-width="100px">
            <el-input v-model="article.press" auto-complete="off"></el-input>
          </el-form-item>


          <el-form-item label="简介" label-width="100px">
            <el-input v-model="article.des" type="textarea" rows="4"></el-input>
          </el-form-item>

          <el-form-item label="所属组" label-width="100px">
            <el-input
              placeholder="输入关键字进行过滤"
              v-model="filterText">
            </el-input>
            <el-tree
              :data="groups"
              :filter-node-method="filterNode"
              show-checkbox
              node-key="id"
              ref="tree"
              highlight-current
              :props="defaultProps"
              :default-checked-keys="chooseGroupIDs"
              :default-expanded-keys="chooseGroupIDs"
              @check-change="handleClick"
            >
            </el-tree>
          </el-form-item>

          <el-form-item label="封面图" label-width="80px">
            <div style="text-align: left;margin: 5px">
              <el-upload
                :limit="picLimit"
                :action="uploadUrl"
                list-type="picture-card"
                :on-preview="handlPicPreview"
                :before-remove="handleBeforeRemove"
                :on-success="handleSuccess"
                :file-list="picFiles"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <div v-show="picVisible" size="tiny">
                <img width="100%" :src="picUrl" alt="">
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialog.dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { baseUrl,baseImgPath } from '../../api/env';
export default {
  data(){
    return {
      baseUrl,
      baseImgPath,
      loading:false,
      picLimit:1,
      uploadUrl:baseUrl+'/common/imageUpload',
      article:{
        id:0,
        title:"",
        author:"佚名",
        des:"",
        publication:"",
        language:"zh_cn",
        group_id:0,
        photo_id:0,
        press:"",
      },
      dialog:{
        dialogFormVisible:false,
        title:"新增书籍",
        close:false,
      },
      pages:{
        offset: 0,
        pageSize: 10,
        page: 1,
        total: 0,
      },
      tableData: [],
      picFiles:[],
      picVisible:false,
      picUrl:"",
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      groups:"",
      chooseGroupIDs:[],
      filterText:''

    }
  },
  created(){
    this.initData();
  },
  methods: {
    initData(){
      this.loading = true;
      var that = this;
      that.$api.get('/admin/article', that.pages, response => {
        if (response.status >= 200 && response.status < 300) {
          var res = response.data;
          if (res.code == 0) {
            that.tableData = res.data.articles.content;
            that.pages.total = res.data.articles.totalElements;
          }else{
            this.$message({
              message: res.msg,
              type: 'warning'
            });
          }
        } else {
          this.$message({
            message: "服务器维护中",
            type: 'error'
          });
        }
        this.loading = false;
      });
    },

    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.pages.page = val;
      this.pages.offset = (val - 1)*this.pages.pageSize;
      this.initData()
    },
    handleBeforeRemove(file, fileList){
      var that = this;
      this.$confirm('此操作将删除该图片, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        that.handleRemove(file, fileList);
      }).catch(() => {

      });
      return false;
    },
    handleRemove(file, fileList) {
      console.log(file);
      var index = this.picFiles.indexOf(file);
      console.log(index);
      if (index > -1) {
        this.picFiles.splice(index, 1);
      }
      console.log(this.picFiles)
    },
    handleSuccess(response,file, fileList) {
      file.id = response.ids[0];
      console.log(response);
      file.url = this.baseUrl+response.thumbnails[0];
      file.downloadUrl = this.baseUrl+response.data[0];

      file.ext = response.exts[0];
      this.picFiles.push(file);
    },
    handlPicPreview(file) {
      console.log(file);
      //BMP,JPG、JPEG、PNG
      if(file.ext.toLowerCase() == ".jpg" || file.ext.toLowerCase() == ".bmp" || file.ext.toLowerCase() == ".jpeg" || file.ext.toLowerCase() == ".png"){
        if(this.picUrl == file.downloadUrl){
          this.picVisible = !this.picVisible;
        }else{
          this.picVisible = true;
        }
        this.picUrl = file.downloadUrl;

      }else{
        this.picVisible = false;
        location.href = file.downloadUrl;
      }

    },
    languageFormat(row,column){
      return row.language == 'zh_cn'?"简体中文":'其他';
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    handleClick(data,checked, node){
      if(checked){
        this.$refs.tree.setCheckedNodes([data]);
      }
    },
    handleEdit(index, row,action) {
      // 加载分组树
      this.chooseGroupIDs=[];
      this.loading = true;
      var that = this;
      that.$api.get('/admin/article/group/tree', {}, response => {
        if (response.status >= 200 && response.status < 300) {
          var res = response.data;
          if (res.code == 0) {
            var tree = res.data.articleGroupsTree;
            console.log(tree);
            if(row != null) {
              that.chooseGroupIDs.push(row.group.id);
            }
            that.groups = JSON.parse(JSON.stringify(tree));


            this.dialog.dialogFormVisible = true;
          }else{
            this.$message({
              message: res.msg,
              type: 'warning'
            });
          }
        } else {
          this.$message({
            message: "服务器维护中",
            type: 'error'
          });
        }
        this.loading = false;
      });


      this.picFiles = new Array();
      if(action == "edit"){
        this.dialog.title = "修改书籍";
        this.article.id = row.id;
        this.article.title = row.title;
        this.article.author = row.author;
        this.article.des = row.des;
        this.article.group_id = ""+row.group.id;
        //this.article.photo_id = ""+row.photo.id;

        if(row.photo != null){//图片处理
          var img = {name: row.photo.name, url: this.baseUrl+row.photo.thumbnail,id:row.photo.id,downloadUrl:this.baseUrl+row.photo.url,ext:row.photo.ext}
          this.picFiles.push(img);
        }

      }else if(action == "add"){
        this.dialog.title = "新增书籍";
        this.article.id = 0;
        this.article.title = "";
        this.article.author = "佚名";
        this.article.des = "";
        this.article.group_id = "0";

      }
    },
    handleSave() {
      this.loading = true;
      var that = this;
      that.article.photo_id = this.picFiles[0].id;
      console.log(this.$refs.tree.getCheckedKeys());
      that.article.group_id = this.$refs.tree.getCheckedKeys()[0];
      that.$api.post('/admin/article', that.article, response => {
        if (response.status >= 200 && response.status < 300) {
          console.log(response.data);
          var res = response.data;
          if (res.code == 0) {
            this.$message({
              message: that.dialog.title+'成功',
              type: 'success'
            });
            this.dialog.dialogFormVisible = false;
            this.initData();
          }else{
            this.$message({
              message: res.msg,
              type: 'warning'
            });
          }
        } else {
          this.$message({
            message: "服务器维护中",
            type: 'error'
          });
        }

      });

      this.loading = false;
    },
    handleDeleteAlert(row) {
      this.$confirm('此操作将删除该书籍, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(row);
      }).catch(() => {

      });
    },
    handleDelete(row) {
      this.loading = true;
      var that = this;
      that.$api.delete('/admin/article/'+row.id, null, response => {
        if (response.status >= 200 && response.status < 300) {
          console.log(response.data);
          var res = response.data;
          if (res.code == 0) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.loading = false;
            this.initData();
          }else{
            this.$message({
              message: res.msg,
              type: 'warning'
            });
          }
        } else {
          this.$message({
            message: "服务器维护中",
            type: 'error'
          });
        }

      });
    },
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
}
</script>

<style lang="less">
@import '../../style/mixin';
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.table_container{
  padding: 20px;
}
.Pagination{
  display: flex;
  justify-content: flex-start;
  margin-top: 8px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
